// pages/myroom/myroom.js
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var WxParse = require('../../wxParse/wxParse.js');
var app = getApp();
var wxAuthFail = false;
var uid='';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    util:util,
    regionList: [],
    regionIndex:0,
    priceList:[],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    var tc = app.get_tc();
    that.setData({
      tc: tc,
    })
    var inviteuid = options.inviteuid ? options.inviteuid : '';
    that.getLoginInfo();
    wx.setNavigationBarTitle({
      title: tc == 1 ? '裝修快速報價' :'Express Quotation',
    })
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      // that.resetNavColor();
    });
    wx.getSystemInfo({
      success: function (res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
        });
      }
    });
    this.getLoginUserInfo('');
    that.setData({
      regionList: [
        {
          region: tc == 1 ? "澳門" : "MACAU",
          priceList: [
            {
              part: 'ampSingleSocket',
              price: 600,
              unit: tc == 1 ? '（600/1個）' : '(600/1pcs)',
              partName: tc == 1 ? '1) 13 Amp 單蘇：' : '1) 13 Amp Single Socket：'
            },
            {
              part: 'ampTwinSocket',
              price: 700,
              unit: tc == 1 ? '（700/1個）' : '(700/1pcs)',
              partName: tc == 1 ? '2) 13 Amp 雙蘇：' : '2) 13 Amp Twin Socket：'
            },
            {
              part: 'emptyOutlet',
              price: 500,
              unit: tc == 1 ? '（500/1個）' : '(500/1pcs)',
              partName: tc == 1 ? '3) Data/Voice 空喉：' : '3) Empty Outlet for Data/Voice：'
            },
            {
              part: 'dataCabling',
              price: 700,
              unit: tc == 1 ? '（700/1條）' : '(700/1strip)',
              partName: tc == 1 ? '4) CAT6 線連制面水晶頭：' : '4) CAT6 Data Cabling with RJ45 Jet and Faceplate：'
            },
            {
              part: 'paintWork', 
              price: 80,
              unit: tc == 1 ? '（80/1尺）最少$8000（100尺）' : '（80/1feet）minimum$8000（100feet）',
              partName: tc == 1 ? '5) 油漆：' : '5) Paint work：'
            },
            {
              part: 'door',
              price: 6000,
              unit: tc == 1 ? '（6000/套）' : '（6000/set）',
              partName: tc == 1 ? '6) 手掃漆空心門（包基本鐵制鉸鏈，門把手和鎖）：' : '6) Spray paint hollow door(included basic ironmongery-hinge and door handle and lock)：'
            },
            {
              part: 'electricApplicant',
              price: 600,
              unit: tc == 1 ? '（600/1件）' : '(600/1pcs)', 
              partName: tc == 1 ? '7）裝燈電器：' : '7）Installation of electric applicant：'
            }
          ]
        },
        {
          region: tc == 1 ? "香港" : "HONGKONG",
          priceList: [
            {
              part: 'ampSingleSocket',
              price: 700,
              unit: tc == 1 ? '（700/1個）' : '(700/1pcs)',
              partName: tc == 1 ? '1) 13 Amp 單蘇：' : '1) 13 Amp Single Socket：'
            },
            {
              part: 'ampTwinSocket',
              price: 800,
              unit: tc == 1 ? '（800/1個）' : '(800/1pcs)',
              partName: tc == 1 ? '2) 13 Amp 雙蘇：' : '2) 13 Amp Twin Socket：'
            },
            {
              part: 'emptyOutlet',
              price: 600,
              unit: tc == 1 ? '（600/1個）' : '(600/1pcs)',
              partName: tc == 1 ? '3) Data/Voice 空喉：' : '3) Empty Outlet for Data/Voice：'
            },
            {
              part: 'dataCabling',
              price: 700,
              unit: tc == 1 ? '（700/1條）' : '(700/1strip)',
              partName: tc == 1 ? '4) CAT6 線連制面水晶頭：' : '4) CAT6 Data Cabling with RJ45 Jet and Faceplate：'
            },
            {
              part: 'paintWork',
              price: 60,
              unit: tc == 1 ? '（60/1尺）最少$6000（100尺）' : '（60/1feet）minimum$6000（100feet）',
              partName: tc == 1 ? '5) 油漆：' : '5) Paint work：'
            },
            {
              part: 'door',
              price: 9000,
              unit: tc == 1 ? '（9000/套）' : '（9000/set）',
              partName: tc == 1 ? '6) 手掃漆空心門（包基本鐵制鉸鏈，門把手和鎖）)：' : '6) Spray paint hollow door(included basic ironmongery-hinge and door handle and lock)：'
            },
            {
              part: 'electricApplicant',
              price: 600,
              unit: tc == 1 ? '（600/1件）' : '(600/1pcs)',
              partName: tc == 1 ? '7）裝燈電器：' : '7）Installation of electric applicant：'
            }
          ]
        },
      ],
    })

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  ////表单提交触发事件
  formSubmit: function (e) {
    var that=this;
    var tc=this.data.tc;
    if (that.data.authData==''){

      that.formSubmitAuth(e);
    }
    // if (that.data.authData.verified != '1'){
    //   wx.showModal({
    //     title: tc == -1 ? 'You are not a member. Please register.' : tc == 1 ?'你不是會員，請註冊':'你不是会员，请注册',
    //   })
    //   return
    // }
    app.saveFormId(e.detail.formId);
    var that = this;
    console.log(e);
    var priceList = that.data.regionList[that.data.regionIndex].priceList
    var res=e.detail.value;
    
    var total=0;
    for(var i=0;i<priceList.length;i++){
      for (var key in res) {
        console.log("key", key)
        var itemValue = res[key];
        if (itemValue && key == priceList[i].part) {
          total+=priceList[i].price * itemValue
        }
        console.log("数据： ", key + ':' + res[key]);
        console.log("数据total： ", total);
      }
      
    }
    that.setData({
      total: total
    })
  },

  //重新读取 登录用户信息
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },
  getLoginInfo: function () {
    var that = this;
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {

        //更新数据
        wxAuthFail = false;
        uid = res.uid;
        that.setData({
          userInfo:res,
          uid: res.uid,
          token: res.token,
          loginUname: res.uname,
          openid: res.wxsmall_openid
        })
        util.api({
          data: {
            "uid": res.uid,
            "publickey": util.publiccode,
            "ac": "userinfo"
          },
          success: function (responseData) {
            console.log(responseData.data);
            that.setData({
              userinfo: responseData.data
            });
          }
        });

      } else {
        wxAuthFail = true;
      }
    }, '')
  },

  bindPickerChange: function (e) {
    var name = e.currentTarget.dataset.name;
    if (name == "region") {
      this.setData({
        regionIndex: e.detail.value
      })
    }
    this.setData({
      total: 0
    })
    console.log("bindPickerChange",e)
  },

  getLoginUserInfo: function (inviteuid) {
    var that = this;
    //调用应用实例的方法获取全局数据
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token
        })
        that.getAuth(res.uid, res.token);
      } else {
        app.reAuthorize(reGetUserInfo);
        wx.hideLoading();
      }
    }, inviteuid);
  },
  //获取用户认证状态
  getAuth: function (uid, token) {
    var that = this;
    var privatekey = utilMd5.hexMD5(uid + 'getUserAuth' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "getUserAuth",
        uid: uid,
        catatype: '20',
        privatekey: privatekey
      },
      method: 'GET',
      success: function (responseData) {
        var data = responseData.data;
        console.log("获取已提交的认证信息：", data);
        if (data && data.res != false && data.realname) {
          //更新数据
          that.setData({
            authData: data,
            userV: data.realname ? data.realname : '',
            phoneV: data.phone ? data.phone : '',
            location: data.location ? data.location : '',
          });

          if (that.data.authData.verified != '1') {

            var tc = that.data.tc;
            // wx.showModal({
            //   title: tc == -1 ? 'You are not a member. Please register.' : tc == 1 ? '你不是會員，請註冊' : '你不是会员，请注册',
            //   confirmText: tc == -1 ? 'REGISTER' : tc == 1 ? '註冊' : '注册',
            //   cancelText: tc == -1 ? 'cancel' : tc == 1 ? '取消' : '取消',
            //   success: function (res) {
            //     if (res.confirm) {
            //       wx.navigateTo({
            //         url: '/pages/agent/agent',
            //       })
            //       console.log('用户点击确定')
            //     } else if (res.cancel) {
            //       wx.navigateBack({
            //         delta: 1
            //       })
            //       // console.log('用户点击取消')
            //     }
            //   }
            // })
            return
          }
        } else {
          that.setData({
            authData: ''
          });
        }
      }
    });
  },

  ////表单提交触发事件
  formSubmitAuth: function (e) {
    app.saveFormId(e.detail.formId);

    var that = this;
    var tc = that.data.tc;
    var res = e.detail.value;
    var username = res.username;
    var mobile = res.mobile;
    var invitemobile = res.invitemobile || '';
    var email = res.email || '';
    var address = res.address || '';
    var selector = '';

    if (username == "") {
      var contentname = tc == 1 ? '姓名不能為空' : '姓名不能为空';
      wx.showModal({
        title: '提示',
        content: contentname,
        showCancel: false,
      })
      return;
    } else if (mobile == "") {
      var contentmobile = tc == 1 ? '手機號不能為空' : '手机号不能为空';
      wx.showModal({
        title: '提示',
        content: contentmobile,
        showCancel: false,
      })
      return;    
    } else if (util.orgid == 20510 && email == "") {
      var contentEmail = (tc == -1 ? 'Email required' : tc == 1 ? '郵箱不能為空' : '邮箱不能为空') + '';
      wx.showModal({
        title: '提示',
        content: contentEmail,
        showCancel: false,
      })
      return;
    } 

    //提交代理商认证请求
    var ac = 'userauth'
    var privatekey = utilMd5.hexMD5(that.data.uid + 'userauth' + that.data.token);
    if (util.orgid == 20510) {
      privatekey = utilMd5.hexMD5(that.data.uid + 'userauth2' + that.data.token);
      ac = 'userauth2';
      selector = util.orgid;
    }
    var params = {
      ac: ac,
      uid: that.data.uid,
      realname: username,
      phone: mobile,
      invitephone: invitemobile,
      email: email,
      address: address,
      catatype: "20",
      orgid: selector ? selector : util.orgid,
      selector: selector ? selector : util.orgid,
      privatekey: privatekey
    };
    console.log('代理商认证：', params);
    // return;

    util.api({
      method: "post",
      data: params,
      success: function (responseData) {
        console.log("提交代理商申请信息：", responseData);
        if (responseData.data.res == false) {
          wx.showModal({
            title: '提示',
            content: "fail",
            showCancel: false,
          })
        } else {
          var contentsucess = tc == 1 ? '申請資料已提交' : '申请资料已提交';
          that.getAuth(that.data.uid, that.data.token);
          wx.showModal({
            title: '提示',
            content: contentsucess,
            showCancel: false,
            success: function (res) {
              // if (res.confirm) {
              //   wx.redirectTo({
              //     url: '/pages/join_pay/join_pay?coin=50&authtype=20',
              //   })
              // }
            }
          })
        }

      },
      fail: function (e) {
        var contentfail = tc == 1 ? '網絡異常,請稍候再試' : '网络异常,请稍候再试';
        wx.showModal({
          title: '提示',
          content: contentfail,
          showCancel: false,
        })

      }
    });
  },
})